// jdbcsh - An interactive shell for JDBC databases
// Copyright (C) 2007 Dan Boitnott
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

package jdbcsh;

import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author Dan Boitnott
 */
public class PreloadTable implements Table {

    private Table tbl;
    private int[] widths;
    private ArrayList<ArrayList> rows = new ArrayList<ArrayList>();
    private Iterator<ArrayList> it;
    private ArrayList<String> row;
    
    public PreloadTable() {}

    public PreloadTable(Table tbl) {
        setTable(tbl);
    }
     
    public void setTable(Table t) {
        tbl = t;
        
        widths = new int[getColumnCount()];
        
        // Set initial column widths based on their label widths
        for (int i = 0; i < getColumnCount(); i++) {
            widths[i] = getColumnLabel(i).length();
        }

        // Build internal table
        ArrayList<String> r;
        String v;
        while (tbl.next()) {
            // Create a new empty row
            r = new ArrayList<String>();

            for (int i = 0; i < getColumnCount(); i++) {                
                v = tbl.getString(i);
                r.add(v);
                widths[i] = Math.max(widths[i], v.length());
            }

            // Add the row to the table
            rows.add(r);
        }

        // Set up the iterator
        it = rows.iterator();
    }      

    public int getColumnCount() {
        return tbl.getColumnCount();
    }

    public int getColumnDisplaySize(int column) {
        return widths[column];
    }

    public String getColumnLabel(int column) {
        return tbl.getColumnLabel(column);
    }

    public String getString(int column) {
        return row.get(column);
    }

    public boolean next() {
        if (!it.hasNext()) return false;
        row = it.next();
        return true;        
    }
}
